package com.starry.core.tenant.core.web;

import com.starry.core.common.constants.CommonConstant;
import com.starry.core.common.tenant.context.TenantContextHolder;
import com.starry.core.redis.service.RedisService;
import com.starry.core.security.context.SecurityInfoContext;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 多租户 Context Web 过滤器
 * 将请求 Header 中的 tenant-id 解析出来，添加到 {@link TenantContextHolder} 中
 *
 * @author xiaoke
 */
public class TenantContextWebFilter extends OncePerRequestFilter {

    public TenantContextWebFilter() {
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        // 设置
        Long tenantId = getTenantId(request);
        if (tenantId != null) {
            // 设置租户上下文
            TenantContextHolder.setTenantId(tenantId);
            // 设置Redis租户ID
            RedisService.TENANT_ID.set(tenantId);
        }
        try {
            chain.doFilter(request, response);
        } finally {
            // 清理
            TenantContextHolder.clear();
            SecurityInfoContext.clear();
            RedisService.TENANT_ID.remove();
        }
    }

    private Long getTenantId(HttpServletRequest request) {
        String tenantIdStr = request.getHeader(CommonConstant.HEADER_TENANTID);
        if (tenantIdStr == null || tenantIdStr.isEmpty()) return null;
        return Long.valueOf(tenantIdStr);
    }
}
